package com.web.exiaodao.remote.controller;

import com.web.exiaodao.business.constant.JConstant;
import com.web.exiaodao.business.entity.Comment;
import com.web.exiaodao.remote.service.ApiCommentService;
import com.web.exiaodao.remote.service.ApiUserService;
import com.web.exiaodao.remote.vo.CommentVo;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.controller.BaseController;
import com.web.webstart.base.util.ReflectionUtils;
import com.web.webstart.base.util.XaUtil;
import com.web.webstart.base.util.jpa.WebUitl;
import com.web.webstart.base.util.result.XaResult;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author zhanglin
 * @version V1.0
 * @Title: ApiCommentController.java
 * @Package com.web.exiaodao.remote.controller
 * @Description: 评论信息接口
 * @date 2016-11-02 15:58:46
 */
@Api(value = "Comment", description = "评论接口", position = 10)
@Controller
@RequestMapping("/api/comment")
public class ApiCommentController extends BaseController {

    private static final Logger LOGGER = Logger.getLogger(ApiCommentController.class);

    @Autowired
    private ApiCommentService commentService;

    @Autowired
    private ApiUserService userService;

    /**
     * @return
     * @Title: findCommentList
     * @Description: 查询所有评论信息
     */
    @ApiOperation(value = "查询所有评论", notes = "查询所有评论信息,当返回的code=1时，取出object进行显示,存放为数组对象")
    @ResponseBody
    @RequestMapping(value = "findCommentList", method = RequestMethod.POST)
    public XaResult<Page<CommentVo>> findCommentList(
            @ApiParam("用户ID,字段名:userId") @RequestParam(value = "userId", required = false) Long userId,
            @ApiParam("评论模块(1：普通商品  2:兑换商品  3：玩 /达人/作品/艺术品   51:住(机构)； 52:机构参观  53：旅游/游学     62:家政护理; 63:医疗服务|医疗康复; 64:护理培训|培训义工),字段名:commentTypes") @RequestParam(value = "commentTypes", required = false) Long commentTypes,
            @ApiParam("字段名:objectId") @RequestParam(value = "objectId", required = false) Long objectId,
            @ApiParam("页号,字段名:nextPage,默认0,从第0页开始") @RequestParam(defaultValue = "0") Integer nextPage,
            @ApiParam("页长,字段名:pageSize,默认10") @RequestParam(defaultValue = "10") Integer pageSize
    ) throws Exception {
        XaResult<Page<CommentVo>> xr = new XaResult<>();
        if (XaUtil.isNotEmpty(userId)) {
            if (XaUtil.isNotEmpty(objectId)) {
                xr.error("objectId必须为空");
                return xr;
            }
            if (XaUtil.isNotEmpty(commentTypes)) {
                xr.error("commentTypes必须为空");
                return xr;
            }
        } else {
            if (XaUtil.isEmpty(objectId)) {
                xr.error("objectId不能为空");
                return xr;
            }
            if (XaUtil.isEmpty(commentTypes)) {
                xr.error("commentTypes不能为空");
                return xr;
            }
        }
        if (commentTypes != null && !JConstant.Order_CommentType.isConstantVal(commentTypes)) {
            xr.error("commentTypes错误!");
        }
        Pageable pageable = WebUitl.buildPageRequest(nextPage, pageSize, "[{property:'createTime',direction:'DESC'}]");
        Map<String, Object> filterParams;
        if (XaUtil.isNotEmpty(userId) && XaUtil.isNotEmpty(commentTypes) && XaUtil.isNotEmpty(objectId)) {
            filterParams = WebUitl.getParametersStartingWith(
                    "{'search_EQ_objectId':'" + objectId + "'" +
                            ",'search_EQ_commentTypes':'" + commentTypes + "'" +
                            ",'search_EQ_userId':'" + userId + "'}", "search_");
        } else if (XaUtil.isNotEmpty(commentTypes) && XaUtil.isEmpty(objectId)) {
            filterParams = WebUitl.getParametersStartingWith(
                    "{'search_EQ_commentTypes':'" + commentTypes + "'" +
                            ",'search_EQ_userId':'" + userId + "'}", "search_");
        } else if (XaUtil.isNotEmpty(objectId) && XaUtil.isEmpty(commentTypes)) {
            filterParams = WebUitl.getParametersStartingWith(
                    "{'search_EQ_objectId':'" + objectId + "'" +
                            ",'search_EQ_userId':'" + userId + "'}", "search_");
        } else if (XaUtil.isNotEmpty(userId)) {
            filterParams = WebUitl.getParametersStartingWith("{'search_EQ_userId':'" + userId + "'}", "search_");
        } else {
            filterParams = WebUitl.getParametersStartingWith(
                    "{'search_EQ_objectId':'" + objectId + "'" +
                            ",'search_EQ_commentTypes':'" + commentTypes + "'}", "search_");
        }
        xr = commentService.findListNEStatusByFilterPage(XaConstant.Status.delete, filterParams, pageable);
        return xr;
    }

    /**
     * @return
     * @Title: save
     * @Description: 新增一条实体
     */
    @ApiOperation(value = "新增评论", notes = "新增评论,当返回的code=1时，保存成功后object返回对象")
    @ResponseBody
    @RequestMapping(value = "" +
            "saveComment", method = RequestMethod.POST)
    public XaResult<CommentVo> saveComment(
            @ApiParam("评论人ID,字段名:userId") @RequestParam(value = "userId") Long userId,
            @ApiParam("评论内容(100字),字段名:comment_Content") @RequestParam(value = "comment_Content") String comment_Content,
            @ApiParam("评论图片（预留字段）（多张，逗号分割）,字段名:commentImgs") @RequestParam(value = "commentImgs", required = false) String commentImgs,
            @ApiParam("类型(1：普通商品  2:兑换商品  3：玩 /达人/作品/艺术品   51:住； 53：旅游/游学     62:家政护理; 63:医疗服务|医疗康复; 64:护理培训|培训义工),字段名:commentTypes") @RequestParam(value = "commentTypes") Integer commentTypes,
            @ApiParam("类型(订单号,字段名:orderDetailId") @RequestParam(value = "orderDetailId") String orderDetailId,
            @ApiParam("卫生等级（5分）预留,字段名:commentHealthClass") @RequestParam(value = "commentHealthClass", required = false) Double commentHealthClass,
            @ApiParam("服务等级（5分）预留,字段名:commentServiceClass") @RequestParam(value = "commentServiceClass", required = false) Double commentServiceClass,
            @ApiParam("环境等级（5分）预留,字段名:commentEnvironmentClass") @RequestParam(value = "commentEnvironmentClass", required = false) Double commentEnvironmentClass,
            @ApiParam("设施等级（5分）预留,字段名:commentFacilityClass") @RequestParam(value = "commentFacilityClass", required = false) Double commentFacilityClass,
            HttpServletRequest request
    ) throws Exception {
        XaResult<CommentVo> xr = new XaResult<>();

        if (XaUtil.isEmpty(userId)) {
            xr.error("userId不能为空");
            return xr;
        }
        if (XaUtil.isEmpty(commentTypes)) {
            xr.error("commentTypes不能为空");
            return xr;
        }
        if (!JConstant.Order_CommentType.isConstantVal(commentTypes)) {
            xr.error("commentTypes错误!");
        }
        if (XaUtil.isEmpty(orderDetailId)) {
            xr.error("oorderDetailId不能为空");
            return xr;
        }
        if (!JConstant.Order_CommentType.isConstantVal(commentTypes)) {
            xr.error("commentTypes不正确");
            return xr;
        }
        if (commentTypes == JConstant.Order_CommentType.HOURSE) {
            if (!isOk(commentHealthClass) || !isOk(commentServiceClass) || !isOk(commentEnvironmentClass) || !isOk(commentFacilityClass)) {
                xr.error("评论的星级只能在[0,5]");
                return xr;
            }
        }
        if (commentTypes == JConstant.Order_CommentType.INSTIBUTION_VISITING) {
            xr.error("机构参观不能评论");
            return xr;
        }
        if (commentTypes == JConstant.Order_CommentType.SERVICE_NURSE_TRANING) {
            xr.error("护理培训|培训义工不能评论");
            return xr;
        }
        if (XaUtil.isEmpty(comment_Content)) {
            xr.error("评论内容不能为空");
            return xr;
        }
        int length = ReflectionUtils.getHibernateColumnAnnotationLength(Comment.class, "comment_Content");
        if (comment_Content.length() > length) {
            xr.error("评论内容不能超过" + length);
            return xr;
        }


        //验证用户是否存在
        userService.findOne(userId);

        Comment model = new Comment();
        model.setComment_Content(comment_Content);
        model.setUserId(userId + "");
        model.setOrderDetailId(orderDetailId);
        model.setCommentImgs(commentImgs);
        model.setCommentTypes(commentTypes);
        model.setCommentHealthClass(commentHealthClass);
        model.setCommentServiceClass(commentServiceClass);
        model.setCommentEnvironmentClass(commentEnvironmentClass);
        model.setCommentFacilityClass(commentFacilityClass);

        return commentService.saveComment(model);
    }

    @ApiOperation(value = "删除评论", notes = "删除评论,当返回的code=1时，保存成功后object返回对象")
    @ResponseBody
    @RequestMapping(value = "deleteCommentById", method = RequestMethod.POST)
    public XaResult<CommentVo> deleteCommentById(
            HttpServletRequest request,
            @ApiParam("评论id,字段名:id,必填,分割") @RequestParam(value = "commentId") Long commentId,
            @ApiParam("用户id,userId") @RequestParam(value = "userId") Long userId
    ) throws Exception {
        XaResult<CommentVo> xr = new XaResult<>();
        if (XaUtil.isEmpty(commentId)) {
            xr.error("commentId不能为空");
            return xr;
        }
        if (XaUtil.isEmpty(userId)) {
            xr.error("userId不能为空");
            return xr;
        }
        xr = commentService.deleteCommentById(commentId, userId);
        return xr;
    }

    private boolean isOk(Double numRate) {
        if (numRate != null && numRate >= 0 && numRate <= 5) {
            return true;
        }
        return false;
    }
}

